package com.wechat.config;

import com.wechat.module.comm.RSACoder;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

import static com.wechat.module.comm.RSACoder.*;

/**
 * 安全认证
 */
public class AuthInterceptor implements HandlerInterceptor {

    private static final String key = "access_key";


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 头部的Authorization值以Bearer开头
        String auth = request.getHeader("Authorization");

         String url = request.getRequestURI();

        System.out.println("auth------>"+auth);
        System.out.println("url------>"+url);
//        if(Const.ignoreUrl.contains(url)){
//            return;
//        }
//
//        boolean flg = false;
//
//        // 请求参数中包含access_key参数
//        String parameter = request.getParameter(key);
//
//
//
//        if (StringUtils.isNotBlank(parameter)) {
//            flg = check(parameter);
//        }
//
//
//
//        // 头部的Authorization值以Bearer开头
//        String auth = request.getHeader("Authorization");
//
//        String Author = request.getHeader("Author");
//        if (StringUtils.isNotBlank(auth)) {
//            flg = check(auth);
//        }
//
//
//        if(!flg){
//            throw new Exception("当前请求不合法！");
//        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

       return true;
    }

    /**
     * 转换时间戳，判断当前请求是否合法
     * @param str
     * @return
     */
    private boolean check(String str) throws Exception {

        //生成密钥对
        Map<String, Object> keyMap = initKey();

        //私钥
        byte[] privateKey = getPrivateKey(keyMap);

        byte[] bytes = Base64.decodeBase64(str);
        // 私钥解析
        byte[] code = RSACoder.decryptByPrivateKey(bytes, privateKey);


        String s = new String(code);

        long time = Integer.valueOf(s);
        long now = new Date().getTime();

        if(time >= now){
            return true;
        }

        return false;
    }




}
